from flask import Flask, send_from_directory, g
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, scoped_session
import sys
import os
import config
from flask_cors import CORS
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from models import Base  # 导入 models.py 中的 Base

def create_app():
    app = Flask(__name__, instance_relative_config=True)
    CORS(app)
    from config import SQLALCHEMY_DATABASE_URI  # 确保可以正确从config.py中导入变量
    print(SQLALCHEMY_DATABASE_URI)  # 打印变量来确认其值
    # print("Database URI:", app.config['SQLALCHEMY_DATABASE_URI'])
    try:
        app.config.from_object(config)
    except ImportError as e:
        print("Failed to import config: {}".format(e))
        exit(1)

    engine = create_engine(app.config['SQLALCHEMY_DATABASE_URI'])
    session_factory = sessionmaker(bind=engine)
    Session = scoped_session(session_factory)

    @app.before_request
    def before_request():
        # 在请求开始之前，为 g 对象添加 session
        g.session = Session()

    @app.teardown_appcontext
    def teardown_request(exception=None):
        # 请求结束时关闭 session
        Session.remove()

    with app.app_context():
        Base.metadata.create_all(engine)

    # 注册数据库
    register_database(app)
    register_extensions(app)
    # 注册蓝图
    register_blueprints(app)


    @app.route('/resource/<path:filename>')
    def static_file(filename):
        print(filename)
        return send_from_directory(app.config['STATIC_FOLDER'], filename)
    return app



def register_blueprints(app):
    # from blueprints.user import user_bp
    from blueprints.problem import problem_bp
    # from blueprints.lessonPlan import lessonPlan_bp
    # from blueprints.questionBank import questionBank_bp
    # from blueprints.chat import chat_bp
    # app.register_blueprint(user_bp)
    app.register_blueprint(problem_bp)
    # app.register_blueprint(lessonPlan_bp)
    # app.register_blueprint(questionBank_bp)
    # app.register_blueprint(chat_bp)


def register_database(app):
    from app.extensions import db
    db.init_app(app)
    with app.app_context():
        db.create_all()


def register_extensions(app):
    from app.extensions import cors
    cors.init_app(app,resources={r'/*': {'origins': '*'}})  # 跨域资源请求
    from app.extensions import login_manager
    login_manager.init_app(app)  # 管理用户登录和认证
